/*
 * Copyright 2012 Faculty of Informatics - Masaryk University.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cz.muni.fi.pa165.creatures.stripes.security;

import cz.muni.fi.pa165.creatures.dto.web.FunctionDTO;
import cz.muni.fi.pa165.creatures.dto.web.PersonDTO;
import cz.muni.fi.pa165.creatures.services.PersonFunctionService;
import cz.muni.fi.pa165.creatures.web.CreatureHuntingActionBeanContext;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.integration.spring.SpringBean;
import net.sourceforge.stripes.security.controller.StripesSecurityManager;
import org.springframework.stereotype.Service;

/**
 * Own implementation of the security manager from the Stripes security plug-in.
 *
 * @author smikloso
 */
@Service
public class SecurityManager implements StripesSecurityManager {

    @SpringBean
    PersonFunctionService personFunctionService;

    @Override
    public boolean isUserInRole(List<String> roles, ActionBeanContext context) {
        return decide(((CreatureHuntingActionBeanContext) context).getUser(),
                roles);
    }

    @Override
    public boolean isUserInRole(List<String> roles, HttpServletRequest request,
            HttpServletResponse response) {
        return decide((PersonDTO) request.getSession()
                .getAttribute("user"), roles);
    }

    private boolean decide(PersonDTO person, List<String> roles) {
        if (person == null) {
            return false;
        }
        List<FunctionDTO> functionsDTO =
                personFunctionService.getFunctions(person.getName());
        if (functionsDTO == null || functionsDTO.size() < 1) {
            return false;
        }

        if (roles == null || roles.size() < 1) {
            return false;
        }

        for (String role : roles) {
            for (FunctionDTO f : functionsDTO) {
                if (f.getName().equals(role)) {
                    return true;
                }
            }
        }
        return false;
    }
}
